#!/bin/bash

# The script creates bulk of yser account listed in the file give as the first argument.
# The format of the file is as follows:
# -------8<-------------
# realname_1
# username_1
# password_1
# realname_2
# username_2
# password_2
# ...
# -------8<-------------
# The number of lines should be a multiple of 3.
# Requirements to the system: Directory /home is mounted with the support of user-quotes.
# Current quotas can be displayed by issuing: sudo repquota /home

# Make sure only root can run our script
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi

# Make sure file with the list of account is specified
if [[ $# -lt 1 || ! -f "$1" ]]; then
   echo "Usage $0 <filename with userdata: <real name>\\n<username>\\n<password>\\n...>" 1>&2
   exit 2
fi

# Initialization
LOG=/dev/null
GROUP=students
GID=$(cat /etc/group | grep "$GROUP:" | cut -d: -f3)
HOMEDIR=/home/$GROUP
SKEL=./skel
if [ ! -d $HOMEDIR ]
then
  	mkdir -p $HOMEDIR
  	[ $? -eq 0 ] && echo "Base directory '$HOMEDIR' has been created."
fi
if [ -z $GID ]
then
	# If the group does not exist we create it
	groupadd $GROUP > $LOG
	[ $? -eq 0 ] && GID=$(cat /etc/group | grep "$GROUP:" | cut -d: -f3)
	[ $? -eq 0 ] && echo "Group '$GROUP' has been created."
fi

# Main loop
i=0
cat "$1" | while read line 
do
	if ((i==0)); then
		# line = real name
		RNAME="$line"
	elif ((i==1)); then
		#line = username
		UNAME="$line"
	else
		#line = password
		EPASSWD=$(mkpasswd "$line")
		PPASSWD=$line
		#remove 
      if [ -n "$(grep "$UNAME:" /etc/passwd)" ]; then
         deluser --remove-home $UNAME > $LOG
      fi
      printf "Creating account %-40s" "'$RNAME' ($UNAME)"
      STATUS="FAILED"
      useradd --gid "$GID" --groups "users" --comment "$RNAME" --base-dir "$HOMEDIR" --skel "$SKEL" --create-home --password "$EPASSWD" --shell /bin/bash "$UNAME"
      [ $? -eq 0 ] && printf "%s\n%s\n" $PPASSWD $PPASSWD | smbpasswd -s -a $UNAME > $LOG
		[ $? -eq 0 ] && quotatool -u $UNAME -b -q 900M -l 1000M /home > $LOG
		[ $? -eq 0 ] && STATUS="OK"
      echo $STATUS
	fi
	((i=(i+1)%3))
done
